package com.hyx.bookManager.utils;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

/**
 * @ClassName RedisUtil
 * @Description TODO
 * @Author 黄乙轩
 * @Date 2021/5/4 0:05
 * @Version 1.0
 **/

@Component
public class RedisUtil {

    @Autowired
    private RedisTemplate redisTemplate;

    public boolean setHash(String key, String val, long time) {
        try {
            redisTemplate.opsForValue().set(key,val,time,TimeUnit.SECONDS);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    public String getHash(String key) {
        String val = null;
        try {
            val = (String) redisTemplate.opsForValue().get(key);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return val;
    }

    public boolean delHash(String key){
        return redisTemplate.delete(key);
    }

    public boolean setBit(String key,long offset,boolean b){
        return redisTemplate.opsForValue().setBit(key,offset,b);
    }

    public boolean getBit(String key,long offset) {
        return redisTemplate.opsForValue().getBit(key,offset);
    }

    public long bitCount(String key) {
        return (long) redisTemplate.execute(new RedisCallback<Long>() {
            @Override
            public Long doInRedis(RedisConnection redisConnection) throws DataAccessException {
                return redisConnection.bitCount(key.getBytes());
            }
        });
    }
}
